package com.wanmait.demo;

import com.wanmait.demo.pojo.Admin;
import com.wanmait.demo.pojo.Role;
import com.wanmait.demo.service.AdminService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;


public class DbRealm extends AuthorizingRealm {

    @Resource
    private AdminService adminService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("doGetAuthorizationInfo....");
        Admin admin = (Admin)principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //设置角色字符串及权限字符串
        Set<String> roles = new HashSet<>();
        Set<String> perms = new HashSet<>();
        Set<Role> roleSet = admin.getRoles();
        roleSet.forEach(role -> {
            roles.add(role.getName());
            role.getPermissions().forEach(permission -> perms.add(permission.getPerm()));
        });

        //设置角色字符串
        info.setRoles(roles);
        //设置权限字符串
        info.setStringPermissions(perms);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("doGetAuthenticationInfo....");

        String username = (String)authenticationToken.getPrincipal();
        System.out.println(username);
        if(username==null)
        {
            throw new AccountException("用户名不能为空");
        }
        Admin admin = adminService.selectByUsername(username);
        System.out.println(admin.getAdminPass());
        if(admin==null)
        {
            throw new UnknownAccountException("没有找到用户名为[" + username + "]的账号");
        }

        return  new SimpleAuthenticationInfo(admin,admin.getAdminPass(),this.getClass().getName());
    }

    //权限修改生效后，立即刷新清空缓存，则可以实现用户不退出生效新的权限
    public void clearCache() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }
}
